package com.mlk.wx;

import com.fasterxml.jackson.core.type.TypeReference;
import com.mlk.core.util.JSONUtils;
import com.mlk.core.util.ServerResponse;
import lombok.Data;
import lombok.ToString;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/getOpenId")
public class WXController {

    /**
     * 服务器端获取openId
     * @param code
     * @return
     */
    @RequestMapping("forBus")
    public ServerResponse getOpenIdForBus(String code){
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> entity = restTemplate.getForEntity("https://api.weixin.qq.com/sns/jscode2session?appid=wx16ee7c1605e7ba12&secret=3e3ddf5c40b4641bfa871b68850d5eae&js_code=" + code + "&grant_type=authorization_code", String.class);
        String response = entity.getBody();
        return ServerResponse.ok(JSONUtils.jSONstringToObj(response,new TypeReference<WXOpenId>(){}).getOpenid());
    }


    /**
     * 客户端获取openId
     * @param code
     * @return
     */
    @RequestMapping("forClient")
    public ServerResponse getOpenIdForClient(String code){
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> entity = restTemplate.getForEntity("https://api.weixin.qq.com/sns/jscode2session?appid=wxc41ba4c21b670e25&secret=b833caea127bb3246be135d260422009&js_code=" + code + "&grant_type=authorization_code", String.class);
        String response = entity.getBody();
        return ServerResponse.ok(JSONUtils.jSONstringToObj(response,new TypeReference<WXOpenId>(){}).getOpenid());
    }

    @Data
    @ToString
    public static class WXOpenId{

        private String session_key;

        private String openid;
    }

}
